package com.jic.member.service.eventHandler.impl.member;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.tuple.Tuple;
import com.jic.member.entity.model.EventListenerContent;
import com.jic.member.service.eventHandler.impl.EventHandlerTemplate;

import java.util.function.Predicate;


/**
 * description: MemberEnventHandlerTemplate
 * date: 2020/6/8 11:28
 * 会员升级降级
 * author: wangys
 * version: 1.0
 */
public abstract class MemberEventHandlerTemplate extends EventHandlerTemplate {

    /**
     * 前置参数校验
     * @return
     */
    @Override
    public Predicate<JSONObject> preValidateParam() {
        return (t) -> {
            return t!= null && t.getInteger("memberNum") != null;
        };
    }

    /**
     * admin 参数[{"eventName":"会员降级1","eventRangeTime":{"f":1591689820000,"s":1593689820000},"memberNum":2}]
     * h5 参数 {"eventCode":"member_upgrade","eventTime":1591689920000,"eventType":1,"thirdUserId":"1","param":{"memberNum":1}}
     * @param content
     * @param branchNodeId
     * @return
     */
    @Override
    public Tuple<Boolean, String> validateParam(EventListenerContent content, Long branchNodeId) {
        Tuple<Boolean, String> match = new Tuple<>();
        match.setF(true);
        JSONArray jsonArray = parseNodeVariable.apply(content, branchNodeId);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject param = (JSONObject)jsonArray.get(i);
            Tuple<Long, Long> eventRangeTime =  param.getObject("eventRangeTime", Tuple.class);
            if(eventRangeTime != null && eventRangeTime.getF() != null){
                long start = eventRangeTime.getF();
                long end = eventRangeTime.getS();
                long now = System.currentTimeMillis();
                if(!(start <= now && now <= end)){
                    match.setF(false);
                    match.setS("时间条件不满足");
                    break;
                }
            }

            if(!param.getInteger("memberNum").equals(content.getParam().getInteger("memberNum"))){
                match.setF(false);
                match.setS("升级降级级数不满足");
                break;
            }

        }
        return match;
    }
}
